package com.xue.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xue.bean.Order;
import com.xue.bean.Product;
import com.xue.service.IOrderProService;
import com.xue.service.IProductService;
import com.xue.service.ISkillService;
import com.xue.util.RedisLock;

@Component
@Service
public class SkillServiceImpl implements ISkillService{

	private static final int TIMOUT = 20 ; //超时时间 10秒
	
	@Autowired
    private RedisLock redisLock;
	
	@Autowired
	private IProductService productService;
	
	@Autowired
	private IOrderProService orderService;
	
	@Override
	public Map<String, String> userShop(Product pro, String userId) {
		Map<String,String> rtnMap = new HashMap<String,String>();
		
		//加锁        
		long time =  TIMOUT;
        if (!redisLock.lock(pro.getProductId(), String.valueOf(time))) {
           // throw new SellException(110, "没抢到，换个姿势再试一遍呀");
        	System.err.println(userId+" : 没抢到，换个姿势再试一遍呀");
        	rtnMap.put("rtnCd", "99");
			rtnMap.put("rntMsg", userId+": 没抢到，换个姿势再试一遍呀");
			return rtnMap;
        }
        Product pMap = productService.selectProById(pro); 
		
       //1. 查询该商品库存，为0则活动结束。
        int stockNum = pMap.getProductCount();
        int saleNum =  pMap.getProductSale();
        int versionId = pMap.getVersionId();
        
        if (stockNum == 0 || stockNum <= saleNum) {
            //库存不足           
        	//System.err.println(userId+" 100: 活动已经结束,请留意下次活动");
        	rtnMap.put("rtnCd", "99");
			rtnMap.put("rntMsg", "活动已经结束,请留意下次活动");
			return rtnMap;
        } else {   
        	Product pMap2 = productService.selectProById(pro);           	
        	int vid = pMap2.getVersionId();
        	if(versionId == vid) {  
        		pMap.setProductId(pro.getProductId());
            	pMap.setProductSale(saleNum+1);
            	pMap.setVersionId((versionId+1));
        		rtnMap = update(pMap,userId);
        		
        	}else if(pMap2.getProductCount()>pMap2.getProductSale()) {
        		
            	pMap2.setProductSale((pMap2.getProductSale()+1));
            	pMap2.setVersionId((vid+1));
        		rtnMap = update(pMap2,userId);
        	}else {
        		rtnMap.put("rtnCd", "99");
    			rtnMap.put("rntMsg", "活动已经结束,请留意下次活动");
    			return rtnMap;
        	}
        }
        //解锁
      	redisLock.unlock(pro.getProductId(), String.valueOf(time));
		return rtnMap;
	}
	/**
	 * 数据更新操作
	 * @param pMap
	 * @param userId
	 * @return
	 */
	@Transactional(rollbackFor = {RuntimeException.class, Error.class})
	public Map<String,String> update(Product pMap,String userId) {
		Map<String,String> rtnMap = new HashMap<String,String>();
		Map<String,String> map = productService.updateProById(pMap); //更新产品库存
		if(map != null && !map.isEmpty() && "00".equals(map.get("rtnCd")))	{
			Order order = new Order();	    	   
			order.setProductId(pMap.getProductId());	    	    
			order.setUserId(userId);
			//保存订单
			Map<String,String> map2 = orderService.saveOrder(order);//保存订单信息
			if(!map2.isEmpty() && "00".equals(map2.get("rtnCd"))){ 			
				rtnMap.put("rtnCd", "00");
				rtnMap.put("rntMsg", "恭喜您，成功抢到商品"+pMap.getProductId());
				return rtnMap;
			}else {
				rtnMap.put("rtnCd", "99");
				rtnMap.put("rntMsg", "订单保存失败！");
				return rtnMap;
			}	    		
		}else {
			rtnMap.put("rtnCd", "99");
			rtnMap.put("rntMsg", "产品更新失败！");
			return rtnMap;
		} 
		
	}
	
	/**
	 * 

	 */
	@Override
	public List<Map<String,String>> skillShop(Product pro,String userId){
//		ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
//		//Map<String,String> map2 = new HashMap<String,String>();
//      	cachedThreadPool.execute(new Runnable(){
//			@Override
//			public void run() {						
//				
//				Map<String,String> map2 = userShop(pro, (userId));
//				list.add(map2);
//			
//			}	        	   
//      	});//创建 n 个线程。
//		      
//		 cachedThreadPool.shutdown(); 
//		 
		 Map<String,String> map2 = userShop(pro, (userId));
			list.add(map2);
			
		return list;
	}
	
	
}
